<template>
    <el-autocomplete v-model="localInputValue" :fetch-suggestions="querySearchList" :placeholder="placeholder" :size="size" clearable @select="handleSelect" @blur="onBlur" @focus="onFocus" @change="handleChange" />
</template>

<script setup>
import { ref, reactive, toRefs, computed } from 'vue'
import store from '@/utils/localStore.ts'

let props = defineProps({
    queryValue: {
        type: String,
        default: ''
    },
    placeholder: {
        type: String,
        default: '请输入'
    },
    size: {
        type: String,
        default: 'small'
    },
    setting: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['update:query-value'])

let state = reactive({
    querySearchList: []
})

let { queryValue, placeholder, setting } = toRefs(props)

let { querySearchList } = toRefs(state)

let settingData = store.getItem(setting.value)
const settingStorage =  settingData? JSON.parse(settingData) : []
state.querySearchList = settingStorage

const localInputValue = computed({
    get: () => props.queryValue,
    set: (value) => emit('update:query-value', value)
})

const onFocus = () => {}

const onBlur = () => {
    let querySearch = querySearchList.value

    let show = querySearch.some((v) => v.value === queryValue.value)
    if (!queryValue.value || show) return

    if (querySearch.length === 10) {
        querySearch.pop()
    }
    let obj = {
        value: queryValue.value,
        link: queryValue.value
    }
    //添加数据到querySearch
    querySearch.unshift(obj)
    state.querySearchList = querySearch
    store.setItem(setting.value, JSON.stringify(querySearchList.value))
}

const handleChange = (e) => {
    emit('update:query-value', e)
}
</script>